package com.cskaoyan.app.service.impl;

// import com.cskaoyan.app.bean.bo.adminbo.AdminAdminBo;
import com.cskaoyan.app.bean.bo.adminbo.AdminCreateBo;
import com.cskaoyan.app.bean.bo.adminbo.AdminDelBo;
import com.cskaoyan.app.bean.bo.adminbo.AdminRoleUpdateBo;
import com.cskaoyan.app.bean.common.BasePageInfo;
import com.cskaoyan.app.bean.po.*;
import com.cskaoyan.app.bean.vo.PermListDataVO;
import com.cskaoyan.app.bean.vo.adminVo.AdminChildren;
import com.cskaoyan.app.bean.vo.adminVo.AdminPermissions;
import com.cskaoyan.app.bean.vo.adminVo.AdminRoleOptVo;
import com.cskaoyan.app.mapper.*;
import com.cskaoyan.app.service.AdminRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author kiggy
 * @since 2022/12/29 11:22
 */
@Service
public class AdminRoleServiceImpl implements AdminRoleService {
    @Autowired
    MarketRoleMapper roleMapper;

    @Autowired
    MarketRoleOptionMapper optionMapper;

    @Autowired
    MarketRoleFunctionMapper functionMapper;

    @Autowired
    MarketRoleApiMapper apiMapper;

    @Autowired
    MarketRolePermissionMapper permissionMapper;

    @Autowired
    MarketPermissionMapper marketPermissionMapper;

    @Autowired
    MarketRoleCategoryMapper categoryMapper;

    @Autowired
    MarketAPIMapper marketAPIMapper;

    @Override
    public PageInfo<MarketRole> listPageAdmins(BasePageInfo basePageInfo) {
        PageHelper.startPage(basePageInfo.getPage(), basePageInfo.getLimit());

        MarketRoleExample marketRoleExample = new MarketRoleExample();
        marketRoleExample.setOrderByClause(basePageInfo.getSort() + " " + basePageInfo.getOrder());
        MarketRoleExample.Criteria criteria = marketRoleExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        List<MarketRole> marketAdmins = roleMapper.selectByExample(marketRoleExample);

        PageInfo<MarketRole> marketAdminPageInfo = new PageInfo<>(marketAdmins);

        return marketAdminPageInfo;
    }

    @Override
    public PageInfo<AdminRoleOptVo> optionRoleList() {
        List<AdminRoleOptVo> marketRoles = optionMapper.selectAllByDel(false);
        PageInfo<AdminRoleOptVo> optVoPageInfo = new PageInfo<>(marketRoles);

        return optVoPageInfo;
    }

    /**
     * marketRole:id,name,desc,addTime,updateTime
     *
     * @param createBo
     * @return
     */
    @Override
    @Transactional
    public List<MarketRole> createRoleData(AdminCreateBo createBo) {
        Date date = new Date();
        MarketRole marketRole = new MarketRole();
        marketRole.setAddTime(date);
        marketRole.setDeleted(false);
        marketRole.setName(createBo.getName());
        marketRole.setDesc(createBo.getDesc());
        marketRole.setUpdateTime(date);
        marketRole.setDeleted(false);
        // 新增——>取出最后添加
        roleMapper.insert(marketRole);
        // 取出
        PageHelper.startPage(1, 1);
        MarketRoleExample marketRoleExample = new MarketRoleExample();
        marketRoleExample.setOrderByClause("add_time desc");
        List<MarketRole> marketAdmins = roleMapper.selectByExample(marketRoleExample);
        PageInfo<MarketRole> marketAdminPageInfo = new PageInfo<>(marketAdmins);
        List<MarketRole> list = marketAdminPageInfo.getList();
        // 同步创建option表
        createOptionDate(list.get(0));
        return list;
    }

    /**
     * TODO:需要和option表一起删除
     *
     * @param adminDelBo
     */
    @Transactional
    @Override
    public void delRoleData(AdminDelBo adminDelBo) {
        // 先取出
        MarketRole marketAdmin = roleMapper.selectByPrimaryKey(adminDelBo.getId());
        // 再删除
        marketAdmin.setDeleted(true);
        roleMapper.updateByPrimaryKeySelective(marketAdmin);
        deloptionDat(adminDelBo);
    }

    @Transactional
    @Override
    public int update(AdminRoleUpdateBo adminBo) {
        // market赋值——>更新
        MarketRole marketRole = new MarketRole();
        marketRole.setName(adminBo.getName());
        marketRole.setDesc(adminBo.getDesc());
        marketRole.setEnabled(adminBo.isEnabled());
        marketRole.setAddTime(adminBo.getAddTime());
        marketRole.setUpdateTime(adminBo.getUpdateTime());
        marketRole.setDeleted(adminBo.isDeleted());

        // 添加进数据库
        MarketRoleExample marketRoleExample = new MarketRoleExample();
        MarketRoleExample.Criteria criteria = marketRoleExample.createCriteria();
        criteria.andIdEqualTo(adminBo.getId());
        int status = roleMapper.updateByExampleSelective(marketRole,marketRoleExample);

        return status;
    }

    private void deloptionDat(AdminDelBo adminDelBo) {
        Integer id = adminDelBo.getId();
        optionMapper.delOptionData(id);
    }


    private void createOptionDate(MarketRole marketRole) {
        Integer id = marketRole.getId();
        String name = marketRole.getName();
        AdminRoleOptVo adminRoleOptVo = new AdminRoleOptVo();
        adminRoleOptVo.setLabel(name);
        adminRoleOptVo.setValue(id);
        adminRoleOptVo.setDeleted(false);
        adminRoleOptVo.setRid(marketRole.getId());
        optionMapper.insert(adminRoleOptVo);
    }

    // public AdminBaseVo permissions(){
    //     AdminBaseVo<Object> adminBaseVo = new AdminBaseVo<>();
    //     return adminBaseVo.ok(null);
    // }

    @Override
    @Transactional
    public AdminPermissions selAllPermissions(String id) {
        AdminPermissions permissions = new AdminPermissions();// 角色级
        // 首先获得角色
        List<AdminChildren> roleChildren = categoryMapper.selAllPermissionRole();
        List<AdminChildren> roleCollect = roleChildren.stream().filter(d -> !d.isDeleted())
                .collect(Collectors.toList());

        // permissions = encapsulationChildren(roleCollect,permissions);
        List<PermListDataVO> permListDataVOS = marketAPIMapper.selectPermLevels();
        permissions.setSystemPermissions(permListDataVOS);
        // 封装assignedPermissions
        // List<String> apis = encapsulationPermission(permissions.getSystemPermissions());
        List<String> api = encapsulationPermission1(id);
        permissions.setAssignedPermissions(api);
        return permissions;
    }

    /**
     * TODO:将insert添加fearch标签，不使用循环
     * 服务端发来新的apis
     * 业务逻辑：将以前的permission全设为del=true
     * @param id:roleId
     * @param apis
     */
    @Override
    @Transactional
    public void updatePermissionData(String id, List<String> apis) {
        MarketPermissionExample permissionExample = new MarketPermissionExample();
        MarketPermissionExample.Criteria criteria = permissionExample.createCriteria();
        criteria.andRoleIdEqualTo(Integer.parseInt(id));
        criteria.andDeletedEqualTo(false);
        List<MarketPermission> permissions = marketPermissionMapper.selectByExample(permissionExample);
        // 进行逻辑删除，将deleted改为true
        for (int i = 0; i < permissions.size(); i++) {
            MarketPermission permission = permissions.get(i);
            // permission.setId(null);
            permission.setDeleted(true);
            permission.setUpdateTime(new Date());
            marketPermissionMapper.updateByPrimaryKeySelective(permission);
        }
        // 进行数据添加
        Iterator<String> apiIterator = apis.iterator();
        MarketPermission marketPermission = new MarketPermission();
        // ArrayList<MarketPermission> permissionsList = new ArrayList<>();
        while (apiIterator.hasNext()){
            String api = apiIterator.next();
            marketPermission.setPermission(api);
            marketPermission.setRoleId(Integer.parseInt(id));
            marketPermission.setUpdateTime(new Date());
            marketPermission.setAddTime(new Date());
            marketPermission.setDeleted(false);
            marketPermissionMapper.insert(marketPermission);
        }
    }

    /**
     * 获得封装好的角色list（systemPermissions）
     * @param adminChildrenList
     */
    public AdminPermissions encapsulationChildren(List<AdminChildren> adminChildrenList,AdminPermissions adminPermissions){
        // 角色
        Iterator<AdminChildren> iterator = adminChildrenList.iterator();
        List<AdminChildren> systemPermissions = new ArrayList<>();
        while (iterator.hasNext()){
            AdminChildren role = iterator.next();
            Integer roleId = role.getRoleId();
            String name = role.getLabel();
            AdminChildren adminChildren = new AdminChildren();
            adminChildren.setId(name);
            adminChildren.setLabel(name);
            adminChildren.setRoleId(roleId);
            // 这里的children是func
            // 一个children有很多个功能，所以应该获得的是功能list
            // 获得封装一步到位
            List<AdminChildren> childrenFuncList =  functionMapper.selFunctionByRoleid(roleId);

            // 获得api表的封装
            Iterator<AdminChildren> chilFuncIterator = childrenFuncList.iterator();
            while (chilFuncIterator.hasNext()){
                AdminChildren funcNext = chilFuncIterator.next();
                Integer funcType = funcNext.getType();
                List<AdminChildren> apiList = apiMapper.selApiByFuncType(funcType);
                // 开始赋children和封装permission表
                Iterator<AdminChildren> chilApiItertor = apiList.iterator();
                while (chilApiItertor.hasNext()){
                    AdminChildren apiChildren = chilApiItertor.next();
                    Integer apiId = apiChildren.getApiId();
                    AdminChildren api = permissionMapper.selPermissionByApiId(apiId);
                    apiChildren.setApi(api.getApi());
                    adminChildren.setId(apiChildren.getId());
                }
                funcNext.setChildren(apiList);
            }

            // 将func赋给role
            adminChildren.setChildren(childrenFuncList);
            // 将role一一添加进systemPermissions的list中
            systemPermissions.add(adminChildren);
            adminPermissions.setSystemPermissions(systemPermissions);
        }
        return adminPermissions;
    }

    /**
     * TODO:Abandoned
     * 封装AdminPermissions的成员变量assignedPermissions
     * @param systemPermissions
     * @return
     */
    private List<String> encapsulationPermission(List<AdminChildren> systemPermissions) {
        Iterator<AdminChildren> roles = systemPermissions.iterator();
        List<AdminChildren> funcList = new ArrayList<>();
        List<Integer> apiList = new ArrayList<>();
        List<String> apiStr = new ArrayList<>();
        // 通过角色获得功能
        while (roles.hasNext()){
            Integer roleId = roles.next().getRoleId();
            // 根据roleIid获得type
            List<AdminChildren> funcTypes = functionMapper.selFuncTypeByRoleId(roleId);
            Iterator<AdminChildren> funcIterator = funcTypes.iterator();
            while (funcIterator.hasNext()){
                funcList.add(funcIterator.next());
            }
        }
        // 通过功能获得api中间表
        Iterator<AdminChildren> funcs = funcList.iterator();
        while (funcs.hasNext()){
            AdminChildren func = funcs.next();
            // 通过type,roleId获得apiId
            List<Integer> apiTypes = apiMapper.selApiTypeByFuncType(func);
            Iterator<Integer> apiIterator = apiTypes.iterator();
            while (apiIterator.hasNext()){
                apiList.add(apiIterator.next());
            }
        }
        Iterator<Integer> apis = apiList.iterator();
        while (apis.hasNext()){
            Integer apiId = apis.next();
            // 通过apiId的sel查询，id = apiId 查询 permission
            MarketPermissionExample permissionExample = new MarketPermissionExample();
            MarketPermissionExample.Criteria criteria = permissionExample.createCriteria();
            criteria.andIdEqualTo(apiId);
            List<MarketPermission> marketPermissions = marketPermissionMapper.selectByExample(permissionExample);
            apiStr.add(marketPermissions.get(0).getPermission());
        }
        return apiStr;
    }

    /**
     * 首先通过id获得opt表的apis的数据，再由apis通过api中间表获得api数组
     * @param id:roleId
     * @return
     */
    private List<String> encapsulationPermission1(String id){
        MarketPermissionExample permissionExample = new MarketPermissionExample();
        MarketPermissionExample.Criteria criteria = permissionExample.createCriteria();
        criteria.andRoleIdEqualTo(Integer.parseInt(id));
        List<MarketPermission> marketPermissions = marketPermissionMapper.selectByExample(permissionExample);
        List<String> permissionCollect = marketPermissions.stream()
                .filter(d -> !d.getDeleted())
                .map(d -> d.getPermission())
                .collect(Collectors.toList());
        return permissionCollect;
    }
}
